package com.blobfish.springbootwebsocket.controller;

import com.blobfish.springbootwebsocket.common.dto.RequestMessage;
import com.blobfish.springbootwebsocket.common.dto.ResponseMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.converter.SimpleMessageConverter;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Controller;

import java.security.Principal;

@Controller
public class WsController {
  @Autowired
  private SimpMessagingTemplate messagingTemplate;

  @MessageMapping("/welcome")
  @SendTo("/topic/getResponse")
  public ResponseMessage say(RequestMessage message) {
    System.out.println(message.getName());
    return new ResponseMessage("Welcome," + message.getName() + "!");
  }

  @MessageMapping("/chat")
  public void handleChat(Principal principal, String msg) {
    if("zhangsan".equals(principal.getName())) {
      messagingTemplate.convertAndSendToUser("lisi", "/queue/notifications", principal.getName() + "给您发来了消息：" + msg);
    } else {
      messagingTemplate.convertAndSendToUser("zhangsan", "/queue/notifications", principal.getName() + "给您发来了消息：" + msg);
    }
  }
}
